package com.wesley.philosopher;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class DiningPhilosophersSample implements Runnable {

    ReentrantLock lock = new ReentrantLock();
    int forks[] = new int[5];
    Phi[] phis = new Phi[5];
    Condition wait = lock.newCondition();
    public DiningPhilosophersSample(){
        for(int i = 0; i < 5; i++) {
            phis[i] = new Phi(i+1);
        }
    }

    class Phi extends Philosopher {

        public Phi(int id) {
            super(id);
        }

        @Override
        public void run() {
            /**
            // Condition 版本 优化 speed = 25 左右
            while(true) {
                try {
                    this.thinking();
                    lock.lockInterruptibly();
                    while (!this.takeLeft(forks)) {
                        wait.await();
                    }
                    while (!this.takeRight(forks)) {
                        wait.await();
                    }
                    lock.unlock();

                    this.eating();

                    lock.lockInterruptibly();
                    this.putLeft(forks);
                    this.putRight(forks);
                    wait.signalAll();
                    lock.unlock();
                    this.finished();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
             */

            /**
             *  speed = 47 左右
             *
            while(true) {
                try {
                    this.thinking();
                    lock.lockInterruptibly();
                    if (!checkLeft(forks) && !checkRight(forks)) {
                        wait.await();
                    }
                    this.takeLeft(forks);
                    this.takeRight(forks);
                    lock.unlock();

                    this.eating();

                    lock.lockInterruptibly();
                    this.putLeft(forks);
                    this.putRight(forks);
                    wait.signalAll();
                    lock.unlock();
                    this.finished();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            */
        }
    }

    @Override
    public void run() {
        //var pool = Executors.newFixedThreadPool(5);
        for(int i = 0; i < 5; i++) {
            new Thread(phis[i]).start();
        }
    }

    public static void main(String[] argv) {
        var solver = new DiningPhilosophersSample();
        solver.run();

    }
}
